package com.usian.admin.gateway.filter;

import com.usian.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
@Log4j2
public class AuthorizeFilter implements GlobalFilter, Ordered {


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取用户的请求路径以及携带的参数
        ServerHttpRequest request = exchange.getRequest();
        // 帮我们做相应到浏览器上 返还 401认证失败
        ServerHttpResponse response = exchange.getResponse();
        //编辑放行路径
        //2.判断当前的请求是否为登录，如果是，直接放行
        if (request.getURI().getPath().contains("/login/in")) {
            //放行
            return chain.filter(exchange);
        }
        //获取token
        String jwtToken = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(jwtToken)) {
            //如果不存在，向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        // jwtToken 是有值的  但是不确定是否合法
        try {
            //直接解析Token 确定合法
            Claims claims = AppJwtUtil.getClaimsBody(jwtToken);
            int result = AppJwtUtil.verifyToken(claims);
            //直接携带token放行
            if (result == 0 || result == -1) {
                Integer id = (Integer) claims.get("id");
                log.info("find userid:{} from uri:{}", request.getURI());
//               重新设置token到header中
                ServerHttpRequest serverHttpRequest = request.mutate().headers(httpHeaders -> {
                    httpHeaders.add("userId", id + "");
                }).build();
                exchange.mutate().request(serverHttpRequest).build();
            } else {
                response.setStatusCode(HttpStatus.UNAUTHORIZED);
                return response.setComplete();
            }
//           request.mutate().header("token",jwtToken);
//           return chain.filter(exchange);
        } catch (Exception e) {
            //如果不存在，向客户端返回错误提示信息
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
//        放行
        return chain.filter(exchange);
    }



    //优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
